package com.libl.realm;

import com.libl.domain.SysUsers;
import com.libl.service.SysUSersService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class MyUserRealm extends AuthorizingRealm {
    @Autowired
    SysUSersService usersService;


    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //根据token获取用户名和密码
        String username = (String) authenticationToken.getPrincipal();
        String password = new String((char[]) authenticationToken.getCredentials());

        //根据用户名查询数据库中用户信息
        SysUsers user = usersService.findByUsername(username);

        //校验用户信息
        //如果user为null说明用户不存在
        if (user==null){
            throw new UnknownAccountException("未知的账户");
        }
        if (user.getStatus()==0){
            throw new LockedAccountException("账户已锁定");
        }
        //user.getPassword() 从数据库中查询到密码
        //对用户输入的密码进行加密，迭代加密 1024次
        Md5Hash md5 = new Md5Hash(password,username,1024);
        //如果密码为空，或者密码不同，说明密码不正确
        if(user.getPassword() == null || !user.getPassword().equals(md5.toString())) {
            throw new CredentialsException("密码不正确");
        }
        //创建返回值对象
        AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, password, user.getRealname());

        return authenticationInfo;
    }
}
